package com.nuctech.hardwaredriver.serialport_library.core;

import android.util.Log;

import com.nuctech.hardwaredriver.serialport_library.core.codec.SerialPortHandler;
import com.nuctech.hardwaredriver.serialport_library.core.codec.SerialPortProtocolDecoder;
import com.nuctech.hardwaredriver.serialport_library.core.exception.SerialPortException;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by 心魂free on 2019/10/30.
 * <p>
 * 读取串口数据线程
 */

public class SerialPortReadThread extends Thread {

    private InputStream readInputStream;
    private SerialPortProtocolDecoder mDecoder;
    private WaitSignalManager mWaitSignalManager;
    private SerialPortHandler mSerialPortHandler;

    public SerialPortReadThread(InputStream mInputStream, SerialPortProtocolDecoder decoder,
                                WaitSignalManager waitSignalManager) {

        readInputStream = mInputStream;
        mDecoder = decoder;

        mWaitSignalManager = waitSignalManager;
    }

    public void setSerialPortHandler(SerialPortHandler serialPortHandler) {
        this.mSerialPortHandler = serialPortHandler;
    }

    @Override
    public void run() {
        super.run();

        while (!interrupted()) {

            mWaitSignalManager.getLock().lock();

            try {

                mWaitSignalManager.getReadCondition().await();
                byte[] receiveData = mDecoder.decoder(readInputStream);
                if (mSerialPortHandler != null) {

                    mSerialPortHandler.messageReceived(receiveData);

                    Thread.sleep(100);

                    mWaitSignalManager.getWriteCondition().signal();

                } else {

                    throw new SerialPortException("SerialPortHandler函数为null");
                }

            } catch (IOException | InterruptedException e) {

                if (e instanceof InterruptedException) {

                    Log.e("TAG", "读取串口数据线程中断");

                } else {

                    e.printStackTrace();
                }

            } finally {

                mWaitSignalManager.getLock().unlock();
            }
        }
    }

    public void stopThread() {

        interrupt();
    }
}
